package com.kuaifawu.lwnlawyerclient.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_home;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_questionDetail;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_reportList;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.Lib.LWNKeyboardListenRelativeLayout;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_questionAdd;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_questionDetail;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class LWNQuestionDetailActivity extends Activity implements View.OnClickListener{

    @ViewInject(R.id.qd_back)
    private ImageButton button_back;
    @ViewInject(R.id.qd_jubao)
    private Button button_jubao;
    @ViewInject(R.id.listView_question)
    private ListView listView_question;
    @ViewInject(R.id.qd_textView)
    private AutoCompleteTextView textView_input;
    @ViewInject(R.id.qd_send)
    private ImageButton imageButton_send;
    @ViewInject(R.id.qd_inputView)
    private RelativeLayout qd_inputView;

    private LWNQuestionDetailActivity activity_qd;

    private LWNAdapter_questionDetail adpter_detail;

    LWNKeyboardListenRelativeLayout relativeLayout;
    private String questionid="";
    private String is_solve="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);
        ViewUtils.inject(this);
        activity_qd = this;
        Intent intent = getIntent();
        Bundle bundle=intent.getExtras();

       questionid = bundle.getString("questionid");
        if(bundle.containsKey("questionsolve")){
            is_solve=intent.getStringExtra("questionsolve");
        }


        inItView();
        getQDFromNetwork();

     }
      private static int Type=-1;
    ArrayList<LWNModel_questionAdd> model_questionAdd=null;
    private void inItView(){
       if(is_solve.equals("1")){
           qd_inputView.setVisibility(View.GONE);
       }
        bitmapUtils=new BitmapUtils(this);
        textView_input.setOnClickListener(this);
        button_jubao.setOnClickListener(this);
        button_back.setOnClickListener(this);
        imageButton_send.setOnClickListener(this);
        listView_question.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(LWNQuestionDetailActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                ArrayList<String> img_thumbnai=model_questionDetail.getQuestion_img();

                model_questionAdd=model_questionDetail.getArray_questionadd();

                if(img_thumbnai!=null&&position==1){
                  //  getPopupShowImg(img_thumbnai);
                    return;
                }

                if(position>0){
                    Type=listView_question.getAdapter().getItemViewType(position);
                    if(img_thumbnai!=null){
                        position=position-2;
                    }else{
                        position=position-1;
                    }
                    if(Type==1){
                        for(int j=0;j<model_questionAdd.size();j++){
                            ArrayList<String> img_thum=model_questionAdd.get(j).getContentadd_img();
                            if(img_thum!=null&&position==j){
                               // getPopupShowImg(img_thum);
                                return;
                            }
                        }
                    }

                }


            }
        });
    }
    public static PopupWindow reportpopupWindow=null;

    private ListView report_list;
    private List<String>list=null;
    private LinearLayout listparent=null;


    /**
     * 弹出举报的窗口
     * @param id
     */
    private void getPopupWindown(String id){
       String arrayList[]=getResources().getStringArray(R.array.report_data);
        list=new ArrayList<>();
        if(list!=null){
            for(int i=0;i<arrayList.length;i++){
                list.add(arrayList[i]);
            }
        }
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
        int screenHeight = getWindowManager().getDefaultDisplay().getHeight();

        View pView=getLayoutInflater().inflate(R.layout.report_popupview,null);
        report_list=(ListView)pView.findViewById(R.id.report_list);
        listparent=(LinearLayout)pView.findViewById(R.id.listparent);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                (screenWidth/6)*5,
                (screenHeight/15)*7);
        listparent.setLayoutParams(layoutParams);
        LWNAdapter_reportList reportAdapter=new LWNAdapter_reportList(this,list,id);
        report_list.setAdapter(reportAdapter);
        report_list.setDividerHeight(2);
        reportpopupWindow=new PopupWindow(pView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,true);
        reportpopupWindow.setBackgroundDrawable(new BitmapDrawable());
        reportpopupWindow.setOutsideTouchable(true);
        reportpopupWindow.setFocusable(true);
        reportpopupWindow.setAnimationStyle(R.style.reportpopwindow_anim_style);
        reportpopupWindow.showAtLocation(button_jubao, Gravity.CENTER, 0, 0);

        pView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(reportpopupWindow.isShowing()){
                    reportpopupWindow.dismiss();
                }

            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.qd_back:
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(textView_input.getWindowToken(), 0);
                finish();
                break;
            case R.id.qd_jubao:
                getPopupWindown(questionid);
                break;
            case R.id.qd_textView:
                listView_question.setSelection(listView_question.getBottom() + 1);
                break;
            case R.id.qd_send:
                if(textView_input.getText().length() == 0){

                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                    toast.showCustom(activity_qd, "请输入内容");

                }
                else{
                    sendMessageToNetwork();
                }

                break;

        }
    }
    private    LWNModel_questionDetail model_questionDetail=null;
    private ArrayList<LWNModel_questionDetail> list_questionDetail=null;
    public void getQDFromNetwork() {
        final ProgressDialog proDialog = android.app.ProgressDialog.show(activity_qd, "", getResources().getString(R.string.toast_wait));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(this)) {
            proDialog.dismiss();
            ToastView_custom toast = new ToastView_custom(this);
            toast.showCustom(this, "检查网络，稍后重试");
            return;
        }
        String string_url = center.getInstance().getQuestionDetail(questionid,activity_qd);
        HttpUtils http = center.getUtils();
        http.configCurrentHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");

                            switch (String.valueOf(string_code)) {
                                case "10000": {
                                    JSONObject json_object = jsonObject.getJSONObject("data");
                                    model_questionDetail = LWNJsonToData.getQuestionDetail(json_object);
                                    list_questionDetail = new ArrayList<LWNModel_questionDetail>();
                                    list_questionDetail.add(model_questionDetail);
                                    adpter_detail = new LWNAdapter_questionDetail(listView_question.getContext(), R.layout.activity_question_detail, list_questionDetail,LWNQuestionDetailActivity.this);
                                    listView_question.setAdapter(adpter_detail);
//                                    listView_question.smoothScrollToPosition(adpter_detail.getCount());
                                    listView_question.setSelection(listView_question.getBottom()+1);
                                    listView_question.setOnScrollListener(new AbsListView.OnScrollListener() {
                                        int listViewScrollState;

                                        @Override
                                        public void onScrollStateChanged(AbsListView view, int scrollState) {
                                            listViewScrollState = scrollState;
                                            switch (scrollState) {
                                                //空闲状态
                                                case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: {
                                                }
                                                break;
                                                //滚动状态
                                                case AbsListView.OnScrollListener.SCROLL_STATE_FLING: {

                                                }
                                                break;
                                                //触摸后滚动
                                                case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: {
                                                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                                                    imm.hideSoftInputFromWindow(textView_input.getWindowToken(), 0);
                                                }
                                                break;
                                            }
                                        }

                                        @Override
                                        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                                        }
                                    });
                                }
                                break;
                                case "10001": {

                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                                case "10003": {
                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                                default: {
                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }

    public void sendMessageToNetwork(){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(activity_qd, "", getResources().getString(R.string.toast_send));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(this)) {
            ToastView_custom toast = new ToastView_custom(this);
            toast.showCustom(this, "检查网络，稍后重试");
            return;
        }
        String url=center.LWNBaseUrl_POST+"lawyanswquestion";
        String content = textView_input.getText().toString();
        RequestParams params = center.getInstance().sendMessage(content ,questionid, activity_qd);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,params,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");

                            //System.out.println(jsonObject);

                            switch (String.valueOf(string_code)) {
                                case "10000": {
                                    JSONObject json_object = jsonObject.getJSONObject("data");
                                    LWNModel_questionDetail model_questionDetail = LWNJsonToData.getQuestionDetail(json_object);
                                    ArrayList<LWNModel_questionDetail> list_questionDetail = new ArrayList<LWNModel_questionDetail>();
                                    list_questionDetail.add(model_questionDetail);
                                    adpter_detail = new LWNAdapter_questionDetail(listView_question.getContext(), R.layout.activity_question_detail, list_questionDetail,LWNQuestionDetailActivity.this);
                                    listView_question.setAdapter(adpter_detail);

                                    listView_question.setSelection(listView_question.getBottom() + 1);
                                    textView_input.setText("");
                                }
                                break;
                                case "10001": {
//
                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                                case "10003": {
//
                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                                default: {
//
                                    ToastView_custom toast = new ToastView_custom(activity_qd.getApplicationContext());
                                    toast.showCustom(activity_qd,string_msg);
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }

    /**
     * 弹出图片查看的窗口
     * @param
     */
    private ViewPager detail_show_image=null;
    private ImageButton detail_showback_image=null;
    private PopupWindow showpopupWindow=null;
    BitmapUtils bitmapUtils =null;
    private LinearLayout line_intor=null;
    private ImageButton line_intor_two=null;
    private ImageButton line_intor_one=null;
    private ProgressBar progress_bar;
    List<View> viewList=new ArrayList<View>();
    public void getPopupShowImg( final ArrayList<String> array_img){
        viewList.clear();
        View pView=getLayoutInflater().inflate(R.layout.popushow_image,null);
        detail_show_image=(ViewPager)pView.findViewById(R.id.detail_show_image);
        detail_showback_image=(ImageButton)pView.findViewById(R.id.detail_showback_image);
        line_intor=(LinearLayout)pView.findViewById(R.id.line_intor);
        progress_bar=(ProgressBar)pView.findViewById(R.id.progress_bar);
        if(array_img!=null){
            for(int i=0;i<array_img.size();i++){
                ImageView imageView=new ImageView(this);
                bitmapUtils.display(imageView, array_img.get(i),new BitmapLoadCallBack<ImageView>() {
                    @Override
                    public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                        progress_bar.setVisibility(View.GONE);
                        imageView.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

                    }

                    @Override
                    public void onPreLoad(ImageView container, String uri, BitmapDisplayConfig config) {
                        super.onPreLoad(container, uri, config);
                        progress_bar.setVisibility(View.VISIBLE);
                    }
                });

                viewList.add(imageView);
            }
        }
        detail_show_image.setAdapter(new LWNAdapter_home(viewList));
        line_intor_one=(ImageButton)pView.findViewById(R.id.detail_showback_image);
        line_intor_two=(ImageButton)pView.findViewById(R.id.detail_showback_image);
        line_intor_one.setOnClickListener(this);
        line_intor_two.setOnClickListener(this);
        showpopupWindow=new PopupWindow(pView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,true);
        showpopupWindow.setBackgroundDrawable(new BitmapDrawable());
        showpopupWindow.setOutsideTouchable(true);
        showpopupWindow.setFocusable(true);
        showpopupWindow.setAnimationStyle(R.style.showImagepopwindow_anim_style);
        showpopupWindow.showAtLocation(button_jubao, Gravity.CENTER, 0, 0);
        detail_showback_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(showpopupWindow.isShowing()){
                    showpopupWindow.dismiss();
                }
            }
        });
        line_intor.getChildAt(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detail_show_image.setCurrentItem(1);
                line_intor.getChildAt(1).setClickable(false);
                line_intor.getChildAt(0).setClickable(true);
            }
        });

        line_intor.getChildAt(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detail_show_image.setCurrentItem(0);
                line_intor.getChildAt(0).setClickable(false);
                line_intor.getChildAt(1).setClickable(true);
            }
        });
        if(array_img.size()==1){
            line_intor.getChildAt(1).setVisibility(View.GONE);
        }else if(array_img.size()==2){
            line_intor.getChildAt(1).setVisibility(View.VISIBLE);
        }
        detail_show_image.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if(position==0){
                    line_intor.getChildAt(position).setPressed(true);
                    line_intor.getChildAt(position+1).setPressed(false);
                    line_intor.getChildAt(position).setClickable(false);
                    line_intor.getChildAt(position+1).setClickable(true);
                }else{
                    line_intor.getChildAt(position).setPressed(true);
                    line_intor.getChildAt(position-1).setPressed(false);
                    line_intor.getChildAt(position).setClickable(false);
                    line_intor.getChildAt(position-1).setClickable(true);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
